package com.cqs.leetcode.string;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.function.Consumer;

/**
 * xw
 * 2022/10/1
 */
public class ReformatPhoneNumber1694 {

    public String reformatNumber(String number) {
        char[] targets = new char[2 * number.length()];
        int idx = -1;
        int digest = -1;
        for (char c : number.toCharArray()) {
            if (c == ' ' || c == '-') continue;
            targets[++idx] = c;
            if (++digest % 3 == 2) {
                targets[++idx] = '-';
            }
        }
        if (idx > 2) {
            if (targets[idx] == '-') {
                //123-345-
                idx -= 1;
            } else if (targets[idx - 1] == '-') {
                //123-345-1 --> 123-34-51
                targets[idx - 1] = targets[idx - 2];
                targets[idx - 2] = '-';
            }
        }
        //123-34
        return new String(targets, 0, idx + 1);
    }

    public String reformatNumber0(String number) {
        number = number.replaceAll(" |-", "");
        int len = number.length() % 3;
        if (len == 0) {
            return reformatNumber0(number, number.length()).toString();
        }
        if (len == 1) {
            StringBuilder s = reformatNumber0(number, number.length() - 4);
            s.append(number.charAt(number.length() - 4));
            s.append(number.charAt(number.length() - 3));
            s.append('-');
            s.append(number.charAt(number.length() - 2));
            s.append(number.charAt(number.length() - 1));
            return s.toString();
        }
        StringBuilder s = reformatNumber0(number, number.length() - 2);
        s.append(number.charAt(number.length() - 2));
        s.append(number.charAt(number.length() - 1));
        return s.toString();
    }


    //3的倍数
    private StringBuilder reformatNumber0(String number, int end) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < end; i++) {
            s.append(number.charAt(i));
            if (i % 3 == 2 && i != number.length() - 1) {
                s.append("-");
            }
        }
        return s;
    }

    public static void main(String[] args) {
        ReformatPhoneNumber1694 r = new ReformatPhoneNumber1694();
        ArrayList<String> cases = Lists.newArrayList("1-23-45 6", "123 4-567", "123 4-5678");
        cases.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                String s1 = r.reformatNumber(s);
                System.out.println(s + "\t" + s1);
            }
        });
    }
}
